/**
 * https://leetcode.cn/problems/subarray-sum-equals-k/submissions/589744899/
 * 560. 和为 K 的子数组
 * medium 2024.12.27
 * 前缀和后缀和差分
 */

class Solution {
public:
    int subarraySum(vector<int>& nums, int k) {
        unordered_map<int,int> mp;
        mp[0]=1;
        int ans=0;
        int num=0;
        for(auto &x:nums){
            num+=x;
            if(mp.find(num-k)!=mp.end())
                ans+=mp[num-k];
            mp[num]++;
        }
        return ans;
    }
};